import {collectlist,canclecollect,collectgoods} from '../utils/api'

//创建同步action  'CANCELCOLLECT'
function create_canclecollect_action(params){
    return {type:'CANCELCOLLECT',params};
}

//创建同步action 'COLLECT
function create_collect_action(params){
    return {type:'COLLECT',params};
}

//创建同步action 'COLLECTLIST'
function create_collectlist_action(params){    
    return {type:'COLLECTLIST',params}
}

//创建异步action
function request_collect_action(params){
    return function(dispatch){
        var userinfo = localStorage.getItem('userinfo') ? JSON.parse(localStorage.getItem('userinfo') ) : {}
        //发 收藏 请求
        collectgoods({userid:userinfo.id,goodid:params.id}).then((res)=>{
            if(res.data.code === 200){
                //触发 同步action
            dispatch( create_collect_action(params) )
            }
        })
    }
}

//创建异步 
function request_canclecollect_action(params){
    return function(dispatch){
        var userinfo = localStorage.getItem('userinfo') ? JSON.parse(localStorage.getItem('userinfo')) : {};
        //发 取消收藏请求
         canclecollect({goodid:params.id,userid:userinfo.id}).then((res)=>{
            if(res.data.code == 200){
                //触发 同步action
                dispatch(create_canclecollect_action(params))
            }
         })
    }
}

//创建异步 action
function request_collectlist_action(params){
   return function(dispatch){
    var userinfo = localStorage.getItem('userinfo') ? JSON.parse(localStorage.getItem('userinfo')) : {};
    //发 收藏列表请求 
    collectlist({userid:userinfo.id}).then((res)=>{
        if(res.data.code === 200){
            //触发同步action
            dispatch(create_collectlist_action(res.data.list) )
        }
    })
   }
}

export {
    request_collect_action,
    request_canclecollect_action,
    request_collectlist_action
}